package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Comment;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.*;

@Service(version = "1.0.0")
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询评论列表
     *
     * @param commentType 评论类型
     * @return {@link Comment}
     */
    @Override
    public Map<String, Object> queryCommentList(Integer page, Integer pagesize, String sortProp, String sortOrder,
                                                int commentType, String messageID) {

        //创建查询分页
        PageRequest pageable = null;

        //如果查询时间是创建时间
        if(StrUtil.isNotEmpty(sortProp)){
            //如果是升序
            if(sortOrder.equals("ascending")){
                pageable= PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.asc(StrUtil.toUnderlineCase(sortOrder))));
                //如果是降序
            }else if(sortOrder.equals("descending")){
                pageable= PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.desc(StrUtil.toUnderlineCase(sortOrder))));
            }
        }

        //这里由于数据库数据不对,将传过来的动态id写死messageID
        Query query=Query.query(Criteria.where("commentType").is(commentType)//  5f5ca81a2a1e592568dd44a3
                .and("publishId").is(new ObjectId("5f5ca81a2a1e592568dd44a3"))).with(pageable);        //查询评论类型为2的评论
        //得到评论信息表
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);


        //查询列表
        Query queryCount = Query.query(Criteria.where("commentType").is(commentType)
                .and("publishId").is(new ObjectId("5f5ca81a2a1e592568dd44a3")));
        //获取当前评论总数
        long count = mongoTemplate.count(queryCount, Comment.class);
        HashMap<String, Object> map = new HashMap<>();

        map.put("commentList",commentList);
        map.put("count",count);
        return map;
    }
}
